package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;

import javax.swing.*;

import bot.City;
import bot.PageGenerator;
import bot.Util;

public class TableButton extends JButton{

	/**
	 * Default Serialization
	 */
	private static final long serialVersionUID = 1L;

	private JTextField url;
	
	private PageGenerator page;
	
	public TableButton(JTextField textCity){
		super("Create Table");
		url = textCity;
		page = new PageGenerator();
		
		addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg) {
				try{
					System.out.println(Util.parseName(url.getText()));
					//make sure input is valid
					if (Util.parseName(url.getText()).equals("")){
						throw new IllegalArgumentException();
					}
					City choosen = new City(url.getText(), BotGui.data);
					//put the population info in the paste buffer
					Util.setPasteBuffer(page.createTable(choosen, getData(BotGui.past, Util.parseName(url.getText()))));
				}
				catch (IllegalArgumentException e){
					e.printStackTrace();
					JOptionPane.showMessageDialog(null, "Invaild city name");
				}
			}
		});
	}
	
	private ArrayList<String> getData(File f, String name){
		ArrayList<String> ret = new ArrayList<String>();
		try {
			BufferedReader reader = new BufferedReader(new FileReader(f));
			//skip two lines since the first line is just headers.
			String line = reader.readLine();
			line = reader.readLine();
			//find the place
			while (line != null){
				if (line.substring(0, name.length()).equals(name)){
					int start = name.length() + 1;
					int end = 0;
					//get the data
					for (int i = name.length() + 1; i < line.length(); i++){
						if (line.charAt(i) == ' '){
							end = i;
							String test = line.substring(start, end);
							if (test.equals("---")){
								break;
							}
							else{
								test = new String(test);
								ret.add(Util.removeCommas(test));
							}
							start = end + 1;
						}
					}
					//end the while loop
					break;
				}
				line = reader.readLine();
			}
			//city wasn't found if the line is null at exit
			if (line == null){
				JOptionPane.showMessageDialog(null, "Historical city data not found");
				throw new IllegalArgumentException("Historical city data not found");
			}
		} 
		catch (FileNotFoundException e){
			e.printStackTrace();
		} 
		catch (IOException e){
			e.printStackTrace();
		}
		return ret;
	}
}
